//
//  IAAAuthCheSecCheckerVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/13.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAAAuthCheSecCheckerVC.h"
#import "IAAAuthCheckModel.h"
#import <MJRefresh.h>
#import "IAAAuthSecCheckerTHeader.h"
#import "IAAAuthSecCheckerTCell.h"

@interface IAAAuthCheSecCheckerVC ()<UITableViewDelegate, UITableViewDataSource>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) IAAAuthCheckCheckerModel *model;

@end

static NSString * const reuseCellId = @"IAAAuthSecCheckerTCell";
static NSString * const reuseHeaderId = @"IAAAuthSecCheckerTHeader";
static NSInteger const kPageSize = 15;  //!< 每次请求的记录数

@implementation IAAAuthCheSecCheckerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //设置导航栏
    [self initNavigationBar];
    //設置子Views
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initNavigationBar {
    self.navigationItem.title = @"选择二审柜员";
}

- (void)initSubViews {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.tableView registerClass:[IAAAuthSecCheckerTHeader class] forHeaderFooterViewReuseIdentifier:reuseHeaderId];
    UINib *cellNib = [UINib nibWithNibName:reuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:reuseCellId];
    self.tableView.tableFooterView = [UIView new];
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉、上拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    
    // 触发刷新
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshWholeView {
    if (self.model.checkerList.count < self.model.totalCount) {
        [self.tableView.mj_footer resetNoMoreData];
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
    [self.tableView reloadData];
}

#pragma mark - <UITableViewDelegate>代理
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    IAAAuthSecCheckerTHeader *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuseHeaderId];
    NSArray<NSString *> *array = @[@"机构号", @"二审柜员号", @"二审柜员待处理任务数"];
    [view configViewWithArrar:array];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    if (self.getSecChecker) {
        self.getSecChecker(self.model.checkerList[indexPath.row]);
        self.getSecChecker = nil;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.checkerList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IAAAuthSecCheckerTCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.model.checkerList.count) {
        [cell configViewWithData:self.model.checkerList[indexPath.row]];
    }
    return cell;
}

#pragma mark - 网络请求
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    NSInteger startIndex = isHeader ? 0 : self.model.checkerList.count;
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckCheckerList];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"token"  : IAA_APP_DELEGATE.token,
                           @"userNo" : IAA_APP_DELEGATE.userNo,
                           @"osName" : @"iOS",
                           @"startIndex" : @(startIndex),
                           @"pageSize": @(kPageSize)};
    
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"二审柜员号返回 %@", responseObject);
        [self tableViewEndRefresh:isHeader];
        IAAAuthCheckCheckerModel *temp = [IAAAuthCheckCheckerModel yy_modelWithJSON:responseObject];
        if (isHeader || !self.model) {
            self.model = temp;
        } else {
            [self.model addMoreWithData:temp];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"二审柜员号失败 %@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

@end
